/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Data;

namespace Xceed.Silverlight.Data
{
  internal abstract class GroupHelperBase : ParentHelper<DataPath>, IGroupDataHelper
  {
    protected GroupHelperBase( IDataHelper childHelper )
      : base( childHelper )
    {
    }

    #region GroupCount

    public int GroupCount
    {
      get
      {
        return this.GroupHandler.GroupDescriptions.Count;
      }
    }

    #endregion GroupCount

    #region GroupHandler Property

    public abstract GroupHandler GroupHandler
    {
      get;
    }

    #endregion GroupHandler Property

    public SortPosition CreateSortPositionForPath( DataPath path, StartPosition startPosition )
    {
      if( path == null )
        throw new ArgumentNullException( "path" );

      List<SortDescription> completeSort = this.CompleteSort.ToList();

      return new SortPosition( completeSort, this.ExtractSortValues( completeSort, path ).ToList(), startPosition );
    }

    public IEnumerable<object> ExtractSortValues( IEnumerable<SortDescription> sort, DataPath path )
    {
      if( path == null )
        throw new ArgumentNullException( "path" );

      foreach( SortDescription sortDescription in sort )
      {
        object sortValue;
        if( !this.TryGetMemberValue( sortDescription.PropertyName, path, out sortValue ) )
          break;

        yield return sortValue;
      }
    }

    public bool IsGroupRelatedPath( DataPath dataPath )
    {
      return this.IsGroupPath( dataPath )
        || this.IsGroupHeaderFooterPath( dataPath );
    }

    public bool IsGroupPath( DataPath dataPath )
    {
      if( dataPath == null )
        throw new ArgumentNullException( "dataPath" );

      return ( dataPath.Depth <= this.GroupCount && dataPath.All( ( item ) => ( item is GroupDataItem ) ) );
    }

    public bool IsGroupHeaderFooterPath( DataPath dataPath )
    {
      if( dataPath == null )
        throw new ArgumentNullException( "dataPath" );

      for( int i = 0; i <= this.GroupCount; i++ )
      {
        if( dataPath[ i ] is HeaderFooterDataItem )
          return true;

        if( i< this.GroupCount && !( dataPath[ i ] is GroupDataItem ) )
          //The specified groupPath does not correspond to the current grouping.
          throw new DataInternalException();
      }

      return false;
    }

    internal int GetGroupPropertyIndex( string groupPropertyName )
    {
      if( groupPropertyName == null )
        throw new ArgumentNullException( "groupPropertyName" );

      int groupPropertyIndex = -1;

      IList<GroupDescription> groupDescriptions = this.GroupHandler.GroupDescriptions;

      for( int i = 0; i < groupDescriptions.Count; i++ )
      {
        GroupDescription groupDescription = groupDescriptions[ i ];
        if( ( groupDescription is PropertyGroupDescription )
          && object.Equals( ( ( PropertyGroupDescription )groupDescription ).PropertyName, groupPropertyName ) )
        {
          groupPropertyIndex = i;
          break;
        }
      }

      return groupPropertyIndex;
    }

    internal object GetMemberValue( DataPath path, GroupDescription groupDescription )
    {
      return this.GetMemberValue( groupDescription.GetPropertyName(), path );
    }

    internal bool TryGetMemberValue( DataPath path, GroupDescription groupDescription, out object value )
    {
      return this.TryGetMemberValue( groupDescription.GetPropertyName(), path, out value );
    }

    internal int CompareValues( object first, object second, GroupDescription groupDescription )
    {
      return this.CompareValues( first, second, groupDescription.GetPropertyName() );
    }

    internal DataPath ReCreateOldPath(
          ItemChangedInfo itemChangedInfo,
          DataPath cachedPath,
          DataPath newCompletePath )
    {
      if( itemChangedInfo == null )
        throw new ArgumentNullException( "itemChangedInfo" );

      if( newCompletePath == null )
        throw new ArgumentNullException( "newCompletePath" );

      if( cachedPath != null && cachedPath.Depth != newCompletePath.Depth )
        throw new ArgumentException( "The specified cached path is not complete.", "cachedPath" );


      //Handle the case of the cached path.
      if( cachedPath != null )
      {
        return cachedPath;
      }

      IList<GroupDescription> grouping = this.GroupHandler.GroupDescriptions;
      DataItem[] longestAvailableOldPath = new DataItem[ newCompletePath.Depth ];

      int pathLength = 0;

      for( int i = 0; i < grouping.Count; i++ )
      {
        object oldValue;
        if( !this.TryGetOldGroupValue( grouping[ i ], itemChangedInfo, newCompletePath[ i ].Data, out oldValue ) )
          break;

        longestAvailableOldPath[ i ] = new GroupDataItem( oldValue );
        pathLength = i;
      }

      return new DataPath( longestAvailableOldPath, pathLength );
    }

    internal bool TryGetOldGroupValue(
          GroupDescription groupDescription,
          ItemChangedInfo itemChangedInfo,
          object newValue,
          out object oldValue )
    {
      if( groupDescription == null )
        throw new ArgumentNullException( "groupDescription" );

      if( itemChangedInfo.TryGetOldValue( groupDescription, out oldValue ) )
        return true;

      if( !itemChangedInfo.GetIsValueChanged( groupDescription ) )
      {
        //Value didn't changed, old value is the same as the new value
        oldValue = newValue;
        return true;
      }

      oldValue = null;
      return false;
    }
  }
}
